package com.oet.web;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.support.PagedListHolder;



import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.oet.persistence.entity.Course;
import com.oet.persistence.entity.CourseSeries;
import com.oet.persistence.entity.Customer;
import com.oet.persistence.entity.MngrAccount;
import com.oet.persistence.entity.MngrRole;
import com.oet.persistence.entity.Teacher;
import com.oet.service.mail.EmailUtility;
import com.oet.service.search.SearchEngine;
import com.oet.utility.RandomString;
import com.oet.webservice.basic.OperationStatus;
import com.oet.webservice.business.WebServiceMngrAccount;
import com.oet.webservice.business.WebMngrAccountListResult;
import com.oet.webservice.business.WebMngrRoleListResult;
import com.oet.webservice.business.AccountMngrService;



/**
 * Process the login request
 *
 * @author Juergen Hoeller
 * @author Ken Krebs
 */
@Controller
//@SessionAttributes({"ydkRoleList"})
public class HomepageController extends WebControllerBase {

//	@Autowired
//	@Qualifier("ydkAccountMngrServiceClient")
//    private AccountMngrService accountMngrServiceClient;
//	
//	public void setYdkAccountMngrServiceClient(AccountMngrService ydkAccountMngrServiceClient) {
//        this.accountMngrServiceClient = ydkAccountMngrServiceClient;
//    }
	
	public HomepageController() {
		this.thisView = "homepage";
		this.fromView = null;
		this.errorView = "homepage";
		this.successView = "homepage";
		this.successViewRedirect = successView + ".do";
		this.homeView = "first_page";
	}
	
	@Autowired
	@Qualifier("accountMngrServiceClient")
    private AccountMngrService accountMngrServiceClient;
	
	
	public void setYdkAccountMngrServiceClient(AccountMngrService accountMngrServiceClient) {
        this.accountMngrServiceClient = accountMngrServiceClient;
    }
	
	
	@Autowired
	protected SearchEngine searchEngine;
	
	public void setSearchEngine(SearchEngine searchEngine) {
        this.searchEngine = searchEngine;
        try {
			searchEngine.init();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	
	@RequestMapping("/homepage.do")
	public ModelAndView homepageHandler() {
		
		//We need to get all the needed information for homepage
		return new ModelAndView(this.successView);
	}
	
	@RequestMapping("/register.do")
	public ModelAndView registerHandler(ServletWebRequest request) {
		
		//We need to get all the needed information for homepage
		String name = request.getParameter("name");
		String email= request.getParameter("email");
		String mobile = request.getParameter("mobile");
		String age = request.getParameter("age");
		
		
		
		Map model = new HashMap();
		if (name == null || name.isEmpty())
		{
			model.put("errorMsg","用户名不能为空: (");
			model.put("name", name);
			model.put("email", email);
			model.put("mobile", mobile);
			model.put("age", age);
			return new ModelAndView("zhuce", model);
		}
		
		
		if (email == null || email.isEmpty())
		{
			model.put("errorMsg","Email地址不能为空: (");
			model.put("name", name);
			model.put("email", email);
			model.put("mobile", mobile);
			model.put("age", age);
			return new ModelAndView("zhuce", model);
		}
		
		if(!EmailUtility.isValid(email))
		{
			model.put("errorMsg","Email地址无效，请检查: (");
			model.put("name", name);
			model.put("email", email);
			model.put("mobile", mobile);
			model.put("age", age);
			return new ModelAndView("zhuce", model);
		}
		
		if (mobile == null || mobile.isEmpty())
		{
			model.put("errorMsg","电话号码不能为空: (");
			model.put("name", name);
			model.put("email", email);
			model.put("mobile", mobile);
			model.put("age", age);
			return new ModelAndView("zhuce", model);
		}
		
		if (!MngrAccountValidator.validateTel(mobile))
		{
			model.put("errorMsg","电话号码格式不正确，请检查: (");
			model.put("name", name);
			model.put("email", email);
			model.put("mobile", mobile);
			model.put("age", age);
			return new ModelAndView("zhuce", model);
		}

		
		if (age != null && !age.isEmpty() && !NumberUtils.isNumber(age))
		{
				model.put("errorMsg","年龄只能为数字，请检查: (");
				model.put("name", name);
				model.put("email", email);
				model.put("mobile", mobile);
				model.put("age", age);
				return new ModelAndView("zhuce", model);
		}
		
		Customer user = this.oetDbMngr.getCustomerByTitle(name);
		
		if (user != null)
		{
			model.put("errorMsg","该用户名已经被注册了，请更换一个: (");
			model.put("name", name);
			model.put("email", email);
			model.put("mobile", mobile);
			model.put("age", age);
			return new ModelAndView("zhuce", model);
		}
		
		user = this.oetDbMngr.getCustomerByEmail(email);
		if (user != null)
		{
			model.put("errorMsg","该Email地址已经被注册了，请更换一个: (");
			model.put("name", name);
			model.put("email", email);
			model.put("mobile", mobile);
			model.put("age", age);
			return new ModelAndView("zhuce", model);
		}
		
		user = this.oetDbMngr.getCustomerByTel(mobile);
		if (user != null)
		{
			model.put("errorMsg","该电话号码已经被注册了，请更换一个: (");
			model.put("name", name);
			model.put("email", email);
			model.put("mobile", mobile);
			model.put("age", age);
			return new ModelAndView("zhuce", model);
		}
		
		
		//Now, we've finished the validation;
		user = new Customer();
		
		user.setName(name);
		user.setEmail(email);
		user.setMobilePhone(mobile);
		user.setAge(Integer.parseInt(age));
		user.setCouresHours(0);
		user.setDescription("这家伙什么都没有留下");
		user.setIsActived(true);
		user.setIsTestFinished(false);
		user.setTotalCourseNumber(0);
		user.setLastAccesseDate(new Date());
		String password = RandomString.getRandomString(6);
		user.setPassword(password);
		
		this.oetDbMngr.storeCustomer(user);
		
		request.getRequest().getSession().setAttribute("userLogin", user);
		
		//OK, now we need to send the password to user's email;
//		EmailUtility.sendRegisterEmailCn(mailService, user);
		
		//Sucess
		return new ModelAndView(new RedirectView("user.do"));
	}
	
	@RequestMapping("/userlogin.do")
	public ModelAndView userLoginHandler() {
		
		//We need to get all the needed information for homepage
		return new ModelAndView("zhuce");
	}
	
	@RequestMapping("/userlogout.do")
	public ModelAndView userLogoutHandler(ServletWebRequest request) {
		Customer user = (Customer) request.getRequest().getSession().getAttribute("userLogin");
		if (user == null)
		{
			
		}
		else
		{
			request.getRequest().getSession().removeAttribute("userLogin");
		}
		//We need to get all the needed information for homepage
		return new ModelAndView("redirect:homepage.do");
	}
	
	@RequestMapping("/user.do")
	public ModelAndView userHandler(ServletWebRequest request) {
		
		
		Customer user = (Customer) request.getRequest().getSession().getAttribute("userLogin");
		if (user == null)
		{
			return new ModelAndView("redirect:register.do?errorMsg=请先登陆");
		}
		
		//OK, now we need to prepare the all the user infomation.
		
		
		return new ModelAndView("user");
		
	}
	
	@RequestMapping("/userLearnMaterial.do")
	public ModelAndView userLearnMaterialHandler(ServletWebRequest request) {
		
		
		Customer user = (Customer) request.getRequest().getSession().getAttribute("userLogin");
		if (user == null)
		{
			return new ModelAndView("redirect:register.do?errorMsg=请先登陆");
		}
		
		//OK, now we need to prepare the all the user infomation.
		
		
		return new ModelAndView("kewaidu");
		
	}
	
	@RequestMapping("/userSelfTest.do")
	public ModelAndView userSelfTestHandler(ServletWebRequest request) {
		
		
		Customer user = (Customer) request.getRequest().getSession().getAttribute("userLogin");
		if (user == null)
		{
			return new ModelAndView("redirect:register.do?errorMsg=请先登陆");
		}
		
		//OK, now we need to prepare the all the user infomation.
		
		
		return new ModelAndView("user_zice");
		
	}
	
	
	
	
	
	@RequestMapping("/teams.do")
	public ModelAndView teamsHandler() {
		
		//We need to get all the information for teachers from Database.
		
		List<Teacher> teachers = (List<Teacher>) this.oetDbMngr.getAllTeachers();
		return new ModelAndView("jiaoshi", "teachers", teachers);
	}
	
	@RequestMapping("/coursegen.do")
	public ModelAndView courseGenHandler() {
		
		//We need to get all the needed information for homepage
		return new ModelAndView("zhuanshukecheng");
	}
	
	
	@RequestMapping("/courseseries.do")
	public ModelAndView courseHandler(ServletWebRequest request) {
		
		
		//We need to get all the needed information for homepage
		String courseSeriesIdS = request.getParameter("id");
		
		Map model = new HashMap();
		
		if (courseSeriesIdS == null || courseSeriesIdS.isEmpty())
		{
			model.put("errorMsg","课程系列ID无效！请重试: (");
			return new ModelAndView("errorPage", model);
		}
		
		Long courseSeriesId = null;
		try{
			courseSeriesId = Long.parseLong(courseSeriesIdS);
		}catch (NumberFormatException e)
		{
			model.put("errorMsg","课程系列ID无效！请重试: (");
			return new ModelAndView("errorPage", model);
		}
		
		CourseSeries entry = this.oetDbMngr.getCourseSeries(courseSeriesId);
		if (entry == null || entry.getId() != courseSeriesId)
		{
			model.put("errorMsg","课程系列ID无效！请重试: (");
			return new ModelAndView("errorPage", model);
		}
		
		List<Course> courseList = this.oetDbMngr.searchCourse(entry, null, 
				null, null, null, null, null, null, null, null, null, null);
		
		model.put("list",courseList);
		model.put("entry", entry);
		
		return new ModelAndView("kc_xiangxi", model);
	}
	
	
	@RequestMapping("/courseSearch.do")
	public ModelAndView courseSearchHandler(ServletWebRequest request) {
		
		//We need to get all the needed information for homepage
		String page = request.getParameter("page");
		String pageNumber = request.getParameter("pageNumber");
		PagedListHolder pageList = null;
		if ((page != null && !page.isEmpty()) || (pageNumber != null&&!pageNumber.isEmpty()))
		{
			pageList = (PagedListHolder) request.getRequest().getSession().getAttribute("pageDataList");
		}
		else
		{
			String paramLevel = request.getParameter("level");
			String paramDate= request.getParameter("date");
			String paramTime = request.getParameter("time");
			String paramKeyword = request.getParameter("keyword");
			String paramAvailable = request.getParameter("available");
			
			Integer level = null;
			
			Integer weekdayFlagStart = null;
			Integer weekdayFlagEnd = null;
			Integer timeFlag = null;
			Boolean isAvailable = null;
			
			if (paramLevel != null && !paramLevel.isEmpty())
			{
				level = Integer.parseInt(paramLevel);
				if (level == 0)
				{
					level = null;
				}
			}
			
			if (paramDate != null && !paramDate.isEmpty())
			{
				int paramIntDate = Integer.parseInt(paramDate);
				int paramIntTime = Integer.parseInt(paramTime);
				
				if (paramIntDate == CourseSeries.WEEKDAY_FLAG_ALL)
				{
					//null
				}
				else if (paramIntDate == CourseSeries.WEEKDAY_FLAG_WEEKEND)
				{
					// <=0
					weekdayFlagStart = CourseSeries.WEEKDAY_FLAG_SAT;
					weekdayFlagEnd = CourseSeries.WEEKDAY_FLAG_SUN;
				}
				else if (paramIntDate == CourseSeries.WEEKDAY_FLAG_WEEKDAY)
				{
					weekdayFlagStart = CourseSeries.WEEKDAY_FLAG_MON;
					weekdayFlagEnd = CourseSeries.WEEKDAY_FLAG_FRI;
				}
				else
				{
					weekdayFlagStart = paramIntDate;
					weekdayFlagEnd = paramIntDate;
				}
				timeFlag = paramIntTime;
				if (timeFlag == 0)
				{
					timeFlag = null;
				}
			}
			
			if (paramAvailable != null && paramAvailable.isEmpty())
			{
				isAvailable = Boolean.parseBoolean(paramAvailable);
			}
			
			Teacher teacher = null;
			if (paramKeyword != null && !paramKeyword.isEmpty())
			{
				teacher = this.oetDbMngr.getTeacherByTitle(paramKeyword);
			}
			List<CourseSeries> list = new ArrayList<CourseSeries>(0);
			if (teacher == null || teacher.getId() == null)
			{
				list = this.oetDbMngr.searchCourseSeries(paramKeyword, null, 
						level, null, null, null, null, null, null, null, null, 
						weekdayFlagStart, weekdayFlagEnd, timeFlag, isAvailable);
				
			}
			else
			{
				list = this.oetDbMngr.searchCourseSeries(null, null, 
						level, null, teacher, null, null, null, null, null, null, 
						weekdayFlagStart, weekdayFlagEnd, timeFlag, isAvailable);
			}
		
		
			pageList = new PagedListHolder(list);
			pageList.setPageSize(8);
		}
		
		if ("last".equals(page)){
			pageList.setPage(pageList.getLastLinkedPage());
		}
		else if(pageNumber != null){
			Integer pageN = new Integer(pageNumber);
			if (pageN.intValue() >= 0)
			{
				pageList.setPage(pageN.intValue());
			}
		}
		
		
		Map model = new HashMap();
		request.getRequest().getSession().setAttribute("pageDataList", pageList);

		
		return new ModelAndView("kcsousuo", model);
	}
	
	@RequestMapping("/selectCourseSeries.do")
	public ModelAndView selectCourseSeriesHandler(ServletWebRequest request) {
		
		
		Customer user = (Customer) request.getRequest().getSession().getAttribute("userLogin");
		if (user == null)
		{
			return new ModelAndView("redirect:register.do?errorMsg=请先登陆");
		}
		
		//OK, now we need to prepare the all the user infomation.
		
		
		return new ModelAndView("user");
		
	}
	
	@RequestMapping("/enterCourse.do")
	public ModelAndView enterCourseHandler(ServletWebRequest request) {
		
		
		Customer user = (Customer) request.getRequest().getSession().getAttribute("userLogin");
		if (user == null)
		{
			return new ModelAndView("redirect:register.do?errorMsg=请先登陆");
		}
		
		//OK, now we need to prepare the all the user infomation.
		
		
		return new ModelAndView("user");
		
	}
	
	
	@RequestMapping("/about.do")
	public ModelAndView aboutHandler() {
		
		//We need to get all the needed information for homepage
		return new ModelAndView("about");
	}
	@RequestMapping("/qa.do")
	public ModelAndView qaHandler() {
		
		//We need to get all the needed information for homepage
		return new ModelAndView("wenti");
	}
	
	
	@RequestMapping("/companyservice.do")
	public ModelAndView comServiceHandler() {
		
		//We need to get all the needed information for homepage
		return new ModelAndView("qieye");
	}




/*
	@RequestMapping("/mngrSystemHome.do")
	public String setupForm(ModelMap model, ServletWebRequest request) {
		return thisView;
	}
	@RequestMapping("/mngrHomePage.do")
	public String setupHomePage(ModelMap model, ServletWebRequest request) {
		return homeView;
	}
	
	@RequestMapping(value="/clearSearchIndex.do", method=RequestMethod.GET)
	public ModelAndView clearSearchIndex(ModelMap model, ServletWebRequest request) {
		
		this.searchEngine.clearRepeatedIndex();
		return null;
	}
	
	@RequestMapping(value="/backupDb.do", method=RequestMethod.GET)
	public ModelAndView backupDbGet(ModelMap model, ServletWebRequest request) {
		
		return new ModelAndView("backup_db");
	}
	
	@RequestMapping(value="/backupDb.do", method=RequestMethod.POST)
	public ModelAndView backupDb(ModelMap model, ServletWebRequest request) {
		String backupFileName = accountMngrServiceClient.backupDb();
		
		if (backupFileName != null)
		{
			model.addAttribute("backupFileName", backupFileName);
			model.addAttribute("operationMsg", "备份成功");
			
		}
		else
		{
			model.addAttribute("operationMsg", "备份失败，请联系管理员");
		}
		return new ModelAndView("backup_db");
	}
	
	@RequestMapping(value="/restoreDb.do", method=RequestMethod.GET)
	public ModelAndView restoreDbGet(ModelMap model, ServletWebRequest request) {
		
		return new ModelAndView("backup_db");
	}
	
	@RequestMapping(value="/restoreDb.do", method=RequestMethod.POST)
	public ModelAndView restoreDb(ModelMap model, ServletWebRequest request) {
		
		MultipartHttpServletRequest multipartRequest =
			(MultipartHttpServletRequest) request.getRequest();
		
		MultipartFile restoreFile = multipartRequest.getFile("restoreFile");
		String checkResult = FileUploadBean.validateFile(restoreFile);
		if (checkResult != null)
		{
			return new ModelAndView("backup_db", "operationMsg", checkResult);
		}
//		
//		try {
//			webInstance.setBookPackage(FileUploadBean.getUploadedFile(contentFile));
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			return new ModelAndView(view, "operationMsg", "上传文件失败");
//		}
		
		OperationStatus os = null;
		try {
			os = accountMngrServiceClient.restoreDb(FileUploadBean.getUploadedFile(restoreFile));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if (os != null && os.getIsSuccessful())
		{
			model.addAttribute("operationMsg", "恢复成功");
			
		}
		else
		{
			model.addAttribute("operationMsg", "恢复失败，请联系管理员");
		}
		return new ModelAndView("backup_db");
	}
	
	@RequestMapping(value="/createYdkAccount.do", method=RequestMethod.GET)
	public ModelAndView createYdkAccountGet(ServletWebRequest request) {

		WebMngrRoleListResult ydkRoleList = accountMngrServiceClient.getAllMngrRoles();
		
		if (ydkRoleList == null || !ydkRoleList.getOs().getIsSuccessful())
		{
			return new ModelAndView("errorPage", "errorMsg","Could not get YdkRoles");
		}
		if (ydkRoleList.getMngrRoles().size() == 0)
		{
			return new ModelAndView("errorPage", "errorMsg","Could not get YdkRoles");
		}
		
		MngrAccountForm ydkAccountForm = new MngrAccountForm();
//		ydkAccount.setYdkRole(new YdkRole());
		Map model = new HashMap();
		
		model.put("dataForm", ydkAccountForm);
		model.put("ydkRoleList", ydkRoleList.getMngrRoles());
		
		return new ModelAndView("system_account_create", model);
	}
	
	@RequestMapping(value="/createYdkAccount.do", method=RequestMethod.POST)
	public ModelAndView createYdkAccountPost(
			@ModelAttribute("dataForm")MngrAccountForm ydkAccountForm,
			BindingResult result,
			@ModelAttribute("ydkRoleList")List<MngrRole> ydkRoleList, 
			ModelMap model, ServletWebRequest request) {
		
		
		MngrAccountValidator.validate(ydkAccountForm, result);

		if (result.hasErrors()) {
			return new ModelAndView("system_account_create");
		}
		
		
		
		//Now we need to check the Unique constrains of YdkAccount.
		WebServiceMngrAccount webAccount = accountMngrServiceClient.getMngrAccountByName(
				ydkAccountForm.getName());
		if (webAccount.getMngrAccount() != null)
		{
			result.rejectValue("account.name", "duplicate", "duplicate");
			return new ModelAndView("system_account_create");
		}
		
		//Input the infor
		MngrAccount ydkAccount = new MngrAccount();
		ydkAccount.setName(ydkAccountForm.getName());
		ydkAccount.setPassword(ydkAccountForm.getPassword());
		ydkAccount.setEmail(ydkAccountForm.getEmail());
		ydkAccount.setIsActived(ydkAccountForm.getIsActived());
		
		for (Long role : ydkAccountForm.getKeys())
		{

			ydkAccount.addRole(role.intValue());

		}
//		ydkAccount.setIsActived(false);
		
		//OK, now it's time to store the ydkAccount;
		webAccount.setMngrAccount(ydkAccount);
		webAccount.setOs(null);
		OperationStatus os = accountMngrServiceClient.storeMngrAccount(webAccount);
		
		//Clear the sessioin;
		request.getRequest().getSession().removeAttribute("ydkRoleList");
		
		if (!os.getIsSuccessful())
		{
			return new ModelAndView("system_account_create",
					"operationMsg", "创建管理帐户失败");
		}
		else
		{
			return new ModelAndView("redirect:listYdkAccount.do", 
					"operationMsg", "创建成功");
		}
		
	}
	
	@RequestMapping(value="/changePassword.do", method=RequestMethod.GET)
	public ModelAndView changePasswordGet(ServletWebRequest request) {

		
//		WebYdkRoleListResult ydkRoleList = ydkAccountMngrServiceClient.getAllYdkRoles();
//		
//		if (ydkRoleList == null || !ydkRoleList.getOs().getIsSuccessful())
//		{
//			return new ModelAndView("errorPage", "errorMsg","Could not get YdkRoles");
//		}
//		if (ydkRoleList.getYdkRoles().size() == 0)
//		{
//			return new ModelAndView("errorPage", "errorMsg","Could not get YdkRoles");
//		}
		
		MngrAccountForm ydkAccountForm = new MngrAccountForm();
//		ydkAccountForm.setAccountId(myAccount.getId());
//		ydkAccountForm.setName(myAccount.getName());
//		ydkAccountForm.setEmail(myAccount.getEmail());
//		ydkAccountForm.setIsActived(myAccount.getIsActived());
//		ydkAccountForm.setRoleId(myAccount.getYdkRole().getId());

		Map model = new HashMap();
		
		model.put("dataForm", ydkAccountForm);
//		model.put("ydkRoleList", ydkRoleList.getYdkRoles());
		
		return new ModelAndView("change_admin_password", model);
	}
	
	
	
	@RequestMapping(value="/changePassword.do", method=RequestMethod.POST)
	public ModelAndView changePasswordPost(
			@ModelAttribute("dataForm")MngrAccountForm ydkAccountForm,
			BindingResult result,
			ModelMap model, ServletWebRequest request) {
		
		MngrAccount myAccount = 
			(MngrAccount)request.getRequest().getSession().getAttribute("userLogIn");
		//Check the new password
		if (!StringUtils.hasLength(ydkAccountForm.getPassword())) {
			result.rejectValue("password", "pwRequired", "请输入旧密码");
		}
		if (!StringUtils.hasLength(ydkAccountForm.getPasswordNew())) {
			result.rejectValue("passwordNew", "pwnRequired", "请输入新密码");
		}
		if (!ydkAccountForm.getPassword().equals(myAccount.getPassword())) {
			result.rejectValue("password", "not equal", "密码错误");
		}
		if (!StringUtils.hasLength(ydkAccountForm.getRepeatedPw())) {
			result.rejectValue("repeatedPw", "required", "请确认新密码");
		}
		if (!ydkAccountForm.getRepeatedPw().equals(ydkAccountForm.getPasswordNew())) {
			result.rejectValue("repeatedPw", "not equal", "新密码不一致");
		}

		if (result.hasErrors()) {
			return new ModelAndView("change_admin_password");
		}
		myAccount.setPassword(ydkAccountForm.getPasswordNew());
		WebServiceMngrAccount instance = new WebServiceMngrAccount(myAccount);
		OperationStatus os = accountMngrServiceClient.updateMngrAccount(instance);
		
		if (!os.getIsSuccessful())
		{
			return new ModelAndView("change_admin_password",
					"operationMsg", "密码修改失败");
		}
		else
		{
			request.getRequest().getSession().setAttribute("userLogIn", myAccount);
			return new ModelAndView("redirect:mngrHomePage.do", 
					"operationMsg", "密码修改成功");
		}
		
	}
	
	
	@RequestMapping(value="/listYdkAccount.do", method=RequestMethod.GET)
	public ModelAndView listYdkAccountGet(ServletWebRequest request) {


		String page = request.getParameter("page");
		String pageNumber = request.getParameter("pageNumber");
		PagedListHolder pageList = null;
		if (page != null || pageNumber != null)
		{
			pageList = (PagedListHolder) request.getRequest().getSession().getAttribute("pageDataList");
		}
		else
		{
			WebMngrAccountListResult ydkAccountList = accountMngrServiceClient.getAllMngrAccounts();
			
			if (ydkAccountList == null || !ydkAccountList.getOs().getIsSuccessful())
			{
				return new ModelAndView("errorPage", "errorMsg","Could not get YdkRoles");
			}
		
		
			pageList = new PagedListHolder(ydkAccountList.getMngrAccounts());
			pageList.setPageSize(8);
		}
		
		if ("last".equals(page)){
			pageList.setPage(pageList.getLastLinkedPage());
		}
		else if(pageNumber != null){
			Integer pageN = new Integer(pageNumber);
			if (pageN.intValue() >= 0)
			{
				pageList.setPage(pageN.intValue());
			}
		}
		
		//Get the modify identifier;
		String accountId = request.getParameter("accountId");
		Map model = new HashMap();
		MngrAccountForm accountForm = new MngrAccountForm();
		if (accountId != null && !accountId.isEmpty())
		{
			Long id = new Long(accountId);
			//user try to modify a record;
			WebServiceMngrAccount webAccount = accountMngrServiceClient.getMngrAccountById(id);
			if (webAccount.getOs().getIsSuccessful())
			{
				accountForm.setAccountId(id);
				accountForm.setName(webAccount.getMngrAccount().getName());
				accountForm.setEmail(webAccount.getMngrAccount().getEmail());
				accountForm.setIsActived(webAccount.getMngrAccount().getIsActived());
				accountForm.setRoleId(webAccount.getMngrAccount().getRole());
			}
			
			WebMngrRoleListResult ydkRoleList = accountMngrServiceClient.getAllMngrRoles();
			
			if (ydkRoleList == null || !ydkRoleList.getOs().getIsSuccessful())
			{
				return new ModelAndView("errorPage", "errorMsg","Could not get YdkRoles");
			}
			if (ydkRoleList.getMngrRoles().size() == 0)
			{
				return new ModelAndView("errorPage", "errorMsg","Could not get YdkRoles");
			}
			model.put("ydkRoleList", ydkRoleList.getMngrRoles());
			request.getRequest().getSession().setAttribute("dataFormSession", webAccount.getMngrAccount());
		}
		model.put("dataForm", accountForm);
		
		
		request.getRequest().getSession().setAttribute("pageDataList", pageList);
		
		return new ModelAndView("system_account_list", model);
	}
	
	
	@RequestMapping(value="/listYdkAccount.do", method=RequestMethod.POST)
	public ModelAndView listYdkAccountDelete(@ModelAttribute("dataForm")MngrAccountForm ydkAccountForm, 
			ServletWebRequest request) {


		for (Long id : ydkAccountForm.getKeys())
		{
			accountMngrServiceClient.deleteMngrAccount(id);
		}
		
		return new ModelAndView("redirect:listYdkAccount.do");
	}
	
	@RequestMapping(value="/modifyYdkAccount.do", method=RequestMethod.POST)
	public ModelAndView modifyYdkAccountPost(@ModelAttribute("dataForm")MngrAccountForm ydkAccountForm, 
			ServletWebRequest request) {

		MngrAccount ydkAccountSession = 
			(MngrAccount)request.getRequest().getSession().getAttribute("dataFormSession");
		//Check the validation of ydkAccountForm and then store ydkAccountForm;
		if (ydkAccountForm.getAccountId() != null)
		{
//			YdkAccount ydkAccount = new YdkAccount();
			ydkAccountSession.setId(ydkAccountForm.getAccountId());
			ydkAccountSession.setEmail(ydkAccountForm.getEmail());
			ydkAccountSession.setName(ydkAccountForm.getName());
			ydkAccountSession.setIsActived(ydkAccountForm.getIsActived());
//			ydkAccountSession.setYdkRole((ydkAccountForm.getRoleId()));
			ydkAccountSession.setRole(0);
			for (int role : ydkAccountForm.getRoles())
			{

				ydkAccountSession.addRole(role);

			}
			WebServiceMngrAccount instance = new WebServiceMngrAccount(ydkAccountSession);
			accountMngrServiceClient.updateMngrAccount(instance);
			
			MngrAccount myAccount = 
				(MngrAccount)request.getRequest().getSession().getAttribute("userLogIn");
			if (myAccount.getId().equals(ydkAccountForm.getAccountId()))
			{
				
				request.getRequest().getSession().setAttribute("userLogIn", instance.getMngrAccount());
			}
		}
		
		return new ModelAndView("redirect:listYdkAccount.do");
	}
	
*/

	

}
